﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Security.Cryptography;

namespace NahidaProject4CSharp.Generic
{
    public class BloomFilter
    {
		private readonly int _size;
		private readonly int _hashCount;
		private readonly BitArray _bits;
		private readonly HashAlgorithm _hashAlgorithm;

		public BloomFilter(int size, int hashCount)
		{
			_size = size;
			_hashCount = hashCount;
			_bits = new BitArray(size);
			_hashAlgorithm = SHA256.Create();
		}

		public void Add(string item)
		{
			var hashes = GetHashes(item);
			foreach (var hash in hashes)
			{
				_bits[hash % _size] = true;
			}
		}

		public bool Contains(string item)
		{
			var hashes = GetHashes(item);
			foreach (var hash in hashes)
			{
				if (!_bits[hash % _size])
				{
					return false;
				}
			}
			return true;
		}

		private IEnumerable<int> GetHashes(string item)
		{
			var bytes = _hashAlgorithm.ComputeHash(System.Text.Encoding.UTF8.GetBytes(item));
			for (int i = 0; i < _hashCount; i++)
			{
				yield return BitConverter.ToInt32(bytes, (i * 4) % bytes.Length);
			}
		}
	}
}
